#include "ProcessModuleEnum.h"

CProcessModuleEnum::CProcessModuleEnum()
{

}

CProcessModuleEnum::~CProcessModuleEnum()
{
    Clear();
}

UINT CProcessModuleEnum::EnumAll( DWORD dwPID )
{
    if ( 0 == dwPID )
    {
        return 0;
    }

    UINT iModuleCount = 0;
    HANDLE hSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, dwPID );

    if ( INVALID_HANDLE_VALUE != hSnap )
    {
        MODULEENTRY32 me;
        me.dwSize = sizeof( MODULEENTRY32 );

        if ( Module32First( hSnap, &me ) )
        {
            do
            {
                PROCESSMODULEINFO* pTmi = new PROCESSMODULEINFO();
                memcpy( &pTmi->me, &me, sizeof( MODULEENTRY32 ) );
                m_vecProcessModule.push_back( pTmi );
                iModuleCount++;

            }
            while ( Module32Next( hSnap, &me ) );
        }

        CloseHandle( hSnap );
    }

    return iModuleCount--;
}

PROCESSMODULEINFO* CProcessModuleEnum::GetAt( UINT uIndex )
{
    if ( m_vecProcessModule.size() > 0 )
    {
        return m_vecProcessModule[uIndex];
    }
    else
        return NULL;
}

void CProcessModuleEnum::Clear()
{
    std::vector<PROCESSMODULEINFO*>::const_iterator cit;

    for ( cit = m_vecProcessModule.begin(); cit != m_vecProcessModule.end(); cit++ )
    {
        PROCESSMODULEINFO* pPro = *cit;

        if ( NULL != pPro )
        {
            delete pPro;
            pPro = NULL;
        }
    }

    m_vecProcessModule.clear();
}